﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using Art_Gallery;
using Newtonsoft.Json.Linq;
using CMCCMicroBlog.ViewModels;


namespace CMCCMicroBlog
{
    public class MainViewModel : INotifyPropertyChanged
    {
        /// <summary>
        /// ItemViewModel 对象的集合。
        /// </summary>
        public static ObservableCollection<FeedModel> HomeTimelineItems { get; set; }
        public static ObservableCollection<FeedModel> AtmeItems { get; set; }
        public static ObservableCollection<FeedModel> CommentItems { get; set; }
        public static ObservableCollection<PrivateMsgModel> PrivateMsgItems { get; set; }
        public static ObservableCollection<FeedModel> FeedItems { get; set; }
        public static ObservableCollection<FeedCommentModel> FeedCommentItems { get; set; }

        public static bool IsHomeTimelineLoaded { get; set; }
        public static bool IsAtmeLoaded { get; set; }
        public static bool IsCommentLoaded { get; set; }
        public static bool IsPrivateMsgLoaded { get; set; }
        public static bool IsFeedLoaded { get; set; }
        public static bool IsFeedCommentItemsLoaded { get; set; }

        public MainViewModel()
        {
            MainViewModel.HomeTimelineItems = new ObservableCollection<FeedModel>();
            MainViewModel.AtmeItems = new ObservableCollection<FeedModel>();
            MainViewModel.CommentItems = new ObservableCollection<FeedModel>();
            MainViewModel.PrivateMsgItems = new ObservableCollection<PrivateMsgModel>();
            MainViewModel.FeedItems = new ObservableCollection<FeedModel>();
            MainViewModel.FeedCommentItems = new ObservableCollection<FeedCommentModel>();
        }

        private string _sampleProperty = "示例运行时属性值";
        /// <summary>
        /// 示例 ViewModel 属性；此属性在视图中用于使用绑定显示它的值
        /// </summary>
        /// <returns></returns>
        public string SampleProperty
        {
            get
            {
                return _sampleProperty;
            }
            set
            {
                if (value != _sampleProperty)
                {
                    _sampleProperty = value;
                    NotifyPropertyChanged("SampleProperty");
                }
            }
        }

        /// <summary>
        /// 加载HomeTimeline的微博,并将其添加到 HomeTimelineItems 集合中。
        /// </summary>
        public static void LoadHomeTimeline(MainPage mp,string sinceId,string maxId,string count)
        {
            mp.loadingProgressBar.Visibility = Visibility.Visible;

            if (sinceId.Equals("") && maxId.Equals(""))
            {
                MainViewModel.HomeTimelineItems.Clear();
            }

            count = count.Equals("") ? "50" : count;
            string sid=AppSettingHelper.GetValueOrDefault<string>(App.SID,"");
            string url = string.Format(App.API_URL+"op=Status.hometimeline&sid={0}&since_id={1}&max_id={2}&count={3}&timestamp={4}", sid,sinceId,maxId,count,DateTime.Now.Millisecond);

            WebClient wc = new WebClient();
            wc.DownloadStringAsync(new Uri(url,UriKind.Absolute));
            wc.DownloadStringCompleted += ((s, e) =>
            {
                JObject jo = JObject.Parse(e.Result);

                JToken data = jo["data"];

                JEnumerable<JToken> feeds = data.Children();

                //string id = "";
                //string user_id = "";
                //string nickname = "";
                //string icon = "";
                //string geography = "";
                //string replieCount = "";
                //string forwardCount = "";
                //string screenname = "";
                //string vtype = "";
                //string vtitle = "";
                //string createTime = "";
                //string source = "";
                //string text = "";
                //string thumbnailPic = "";
                //string bmiddlePic = "";
                //string originalPic = "";

                foreach (JToken feed in feeds)
                {
                    FeedModel f=feed.ToObject<FeedModel>();
                    MainViewModel.HomeTimelineItems.Add(f);
                    /*
                    id = feed["id"].ToString();
                    user_id = feed["user_id"].ToString();
                    nickname = feed["nickname"].ToString();
                    icon = feed["icon"].ToString();
                    geography = feed["geography"].ToString();
                    replieCount = feed["replies_count"].ToString();
                    forwardCount = feed["forward_count"].ToString();
                    screenname = feed["screenname"].ToString();
                    vtype = feed["vtype"].ToString();
                    vtitle = feed["vtitle"].ToString();
                    createTime = feed["create_time"].ToString();
                    source = feed["source"].ToString();
                    text = feed["text"].ToString();
                    thumbnailPic = "";
                    bmiddlePic = "";
                    originalPic = "";

                    try
                    {
                        thumbnailPic = feed["thumbnail_pic"].ToString();
                        bmiddlePic = feed["bmiddle_pic"].ToString(); ;
                        originalPic = feed["original_pic"].ToString();
                    }
                    catch (Exception exx)
                    {
                        thumbnailPic = bmiddlePic = originalPic = "/Images/picture.png";
                        Debug.WriteLine(exx.Message + "\n" + exx.StackTrace);
                    }
                    finally
                    {
                        MainViewModel.Items.Add(new ItemViewModel() { NickName = nickname, FeedText = text, FeedImageUri = new Uri(thumbnailPic, UriKind.RelativeOrAbsolute), OriginalImageUri = new Uri(originalPic, UriKind.RelativeOrAbsolute), IconImageUri = new Uri(icon, UriKind.RelativeOrAbsolute) });
                    }*/
                }

            MainViewModel.IsHomeTimelineLoaded = true;
            mp.loadingProgressBar.Visibility = Visibility.Collapsed;
        });
        }

        /// <summary>
        /// 加载@我的微博,并将其添加到 AtmeItems 集合中。
        /// </summary>
        public static void LoadAtme(MainPage mp, string sinceId, string maxId, string count)
        {
            mp.loadingProgressBar.Visibility = Visibility.Visible;

            if (sinceId.Equals("") && maxId.Equals(""))
            {
                MainViewModel.AtmeItems.Clear();
            }

            count = count.Equals("") ? "50" : count;

            string query = string.Format("op=Status.atme&since_id={0}&max_id={1}&count={2}&timestamp={3}", sinceId, maxId, count, DateTime.Now.Millisecond);

            WebClient wc = new WebClient();
            wc.DownloadStringAsync(App.BuildQueryUri(query));
            wc.DownloadStringCompleted += ((s, e) =>
            {
                JObject jo = JObject.Parse(e.Result);

                JToken data = jo["data"];

                JEnumerable<JToken> feeds = data.Children();

                foreach (JToken feed in feeds)
                {
                    FeedModel f = feed.ToObject<FeedModel>();
                    MainViewModel.AtmeItems.Add(f);
                }

                MainViewModel.IsAtmeLoaded = true;
                mp.loadingProgressBar.Visibility = Visibility.Collapsed;
            });
        }

        /// <summary>
        /// 加载Comment到我的微博,并将其添加到 CommentItems 集合中。
        /// </summary>
        public static void LoadComment(MainPage mp, string sinceId, string maxId, string count)
        {
            mp.loadingProgressBar.Visibility = Visibility.Visible;

            if (sinceId.Equals("") && maxId.Equals(""))
            {
                MainViewModel.CommentItems.Clear();
            }

            count = count.Equals("") ? "50" : count;

            string query = string.Format("op=Comment.tome&since_id={0}&max_id={1}&count={2}&timestamp={3}", sinceId, maxId, count, DateTime.Now.Millisecond);

            WebClient wc = new WebClient();
            wc.DownloadStringAsync(App.BuildQueryUri(query));
            wc.DownloadStringCompleted += ((s, e) =>
            {
                JObject jo = JObject.Parse(e.Result);

                JToken data = jo["data"];

                JEnumerable<JToken> feeds = data.Children();

                foreach (JToken feed in feeds)
                {
                    FeedModel f = feed.ToObject<FeedModel>();
                    MainViewModel.CommentItems.Add(f);
                }

                MainViewModel.IsCommentLoaded = true;
                mp.loadingProgressBar.Visibility = Visibility.Collapsed;
            });
        }

        /// <summary>
        /// 加载私信,并将其添加到 PrivateMsgItems 集合中。
        /// </summary>
        public static void LoadPrivateMsg(MainPage mp, string sinceId, string maxId, string count)
        {
            mp.loadingProgressBar.Visibility = Visibility.Visible;

            if (sinceId.Equals("") && maxId.Equals(""))
            {
                MainViewModel.PrivateMsgItems.Clear();
            }

            count = count.Equals("") ? "50" : count;

            string query = string.Format("op=Message.userList&since_id={0}&max_id={1}&count={2}&timestamp={3}", sinceId, maxId, count, DateTime.Now.Millisecond);

            WebClient wc = new WebClient();
            wc.DownloadStringAsync(App.BuildQueryUri(query));
            wc.DownloadStringCompleted += ((s, e) =>
            {
                JObject jo = JObject.Parse(e.Result);

                JToken data = jo["data"];

                JEnumerable<JToken> feeds = data.Children();

                foreach (JToken feed in feeds)
                {
                    PrivateMsgModel f = feed.ToObject<PrivateMsgModel>();
                    MainViewModel.PrivateMsgItems.Add(f);
                }

                MainViewModel.IsPrivateMsgLoaded = true;
                mp.loadingProgressBar.Visibility = Visibility.Collapsed;
            });
        }

        /// <summary>
        /// 加载单条微博,并将其添加到 FeedItems 集合中。
        /// </summary>
        public static void LoadFeed(MainPage mp, FeedModel f)
        {
            mp.loadingProgressBar.Visibility = Visibility.Collapsed;

            MainViewModel.FeedItems.Clear();
            MainViewModel.FeedItems.Add(f);

            MainViewModel.IsFeedLoaded = true;
            mp.loadingProgressBar.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 加载单条微博的评论,并将其添加到 FeedCommentItems 集合中。
        /// </summary>
        public static void LoadFeedComment(MainPage mp, FeedModel f)
        {
            mp.loadingProgressBar.Visibility = Visibility.Collapsed;

            MainViewModel.FeedCommentItems.Clear();
            //MainViewModel.FeedCommentItems.Add();

            MainViewModel.IsFeedLoaded = true;
            mp.loadingProgressBar.Visibility = Visibility.Collapsed;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}